package com.wr.servlet;

import com.alibaba.fastjson.JSON;
import com.wr.factory.BeanFactory;
import com.wr.pojo.Result;
import com.wr.service.AccountService;
import com.wr.service.impl.AccountServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王瑞
 * @descreption:
 * @date 2020/2/14  22:30
 */
@WebServlet(name = "transferServlet",urlPatterns = "/transferServlet")
public class MyServlet extends HttpServlet {

     private AccountService accountService = null;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");

        Result result = new Result();
        try {
            accountService.transfer(fromCardNo,toCardNo,Integer.parseInt(moneyStr));
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMsg(e.getMessage());
        }
        String s = JSON.toJSONString(result);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(s);

    }

    @Override
    public void init() throws ServletException {
        System.out.println("servlet容器初始化");
        try {
            accountService = BeanFactory.getBean(AccountServiceImpl.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
